package com.jzhao.gper.spring.v2.aop.support;

import com.jzhao.gper.spring.v2.aop.aspect.JZAdvice;
import com.jzhao.gper.spring.v2.aop.config.JZAopConfig;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JZAdvisedSupport {
    private JZAopConfig config;
    private Object target;
    private Class targetClass;
    private Pattern pointCutClassPattern;

    private Map<Method,Map<String,JZAdvice>> methodCache;

    public JZAdvisedSupport(JZAopConfig config) {
        this.config = config;
    }

    public Object getTarget() {
        return target;
    }

    public void setTarget(Object target) {
        this.target = target;
        parse();
    }

    //解释配置文件的方法
    private void parse() {
        //把Spring的Excpress变成Java能够识别的正则表达式
        String pointCut = config.getPointCut()
                .replaceAll("\\.", "\\\\.")
                .replaceAll("\\\\.\\*", ".*")
                .replaceAll("\\(", "\\\\(")
                .replaceAll("\\)", "\\\\)");

        //保存专门匹配class的正则
        String pointCutForClassRegex = pointCut.substring(0,pointCut.lastIndexOf("\\(")-4);
        pointCutClassPattern = Pattern.compile("class "+pointCutForClassRegex.substring(pointCutForClassRegex.lastIndexOf(" ") + 1));

        methodCache = new HashMap<Method, Map<String, JZAdvice>>();
        Pattern pointCutPattern = Pattern.compile(pointCut);

        try {
            Class aspectClass = Class.forName(this.config.getAspectClass());
            Map<String,Method> aspectMethods = new HashMap<String, Method>();
            for (Method method : aspectClass.getMethods()) {
                aspectMethods.put(method.getName(),method);
            }

            //将目标类的所有方法拿出来，与切点进行匹配
            for (Method method : this.targetClass.getMethods()) {
                String methodString = method.toString();
                if(methodString.contains("throws")){
                    methodString = methodString.substring(0,methodString.lastIndexOf("throws")).trim();
                }

                Matcher matcher = pointCutPattern.matcher(methodString);
                //如果可以匹配上
                if(matcher.matches()){
                    Map<String,JZAdvice> advices = new HashMap<String, JZAdvice>();

                    if(!(null == config.getAspectBefore() || "".equals(config.getAspectBefore()))){
                        advices.put("before",new JZAdvice(aspectClass.newInstance(),aspectMethods.get(config.getAspectBefore())));
                    }

                    if(!(null == config.getAspectAfter() || "".equals(config.getAspectAfter()))){
                        advices.put("after",new JZAdvice(aspectClass.newInstance(),aspectMethods.get(config.getAspectAfter())));
                    }

                    if(!(null == config.getAspectAfterThrow() || "".equals(config.getAspectAfterThrow()))){
                        JZAdvice advice = new JZAdvice(aspectClass.newInstance(),aspectMethods.get(config.getAspectAfter()));
                        advice.setThrowName(config.getAspectAfterThrowingName());
                        advices.put("after",advice);
                    }

                    methodCache.put(method,advices);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Class getTargetClass() {
        return targetClass;
    }

    public void setTargetClass(Class targetClass) {
        this.targetClass = targetClass;
    }

    public Map<String,JZAdvice> getAdvices(Method method) throws Exception {
        Map<String,JZAdvice> cache = methodCache.get(method);
        //感觉没什么用
        /*if(null == cache){
            Method m = targetClass.getMethod(method.getName(),method.getParameterTypes());
            cache = methodCache.get(m);
            this.methodCache.put(m,cache);
        }*/
        return cache;
    }

    public boolean pointCutMatch() {
        return pointCutClassPattern.matcher(this.targetClass.toString()).matches();
    }
}
